package com.org.controller.errorController;

import com.org.entity.ResponseData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Rainy-Heights
 * @version 1.0
 * @Date 2023/3/7 6:49
 */
@ControllerAdvice
//设置异常处理 的响应界面
public class ErrorController {
    @ExceptionHandler(Exception.class)
    public String GetException(Exception e, Model model) {
         e.printStackTrace();
         model.addAttribute("exception",e);
         return "/error/pages-500";//服务器异常错误。
    }

    //404（之后完善错误页面业务逻辑）
    //注意，不同错误之间异常类型不能一致！
    @ExceptionHandler(NoHandlerFoundException.class)
    public String notfound(HttpServletRequest request,Exception e){
        Logger logger= LoggerFactory.getLogger(ErrorController.class);
        logger.error("Not Found Error Has Happened",e);
        ResponseData responseData=new ResponseData();
        responseData.setMessage(e.getMessage());
        if (e instanceof org.springframework.web.servlet.NoHandlerFoundException){
            responseData.setCode(404);
        }else {
            responseData.setCode(500);
        }
        responseData.setData(null);
        responseData.setStatus(true);
        return "/error/pages-404";
    }
}
